import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {


    public static class SelectPro implements Runnable {

        private int index;
        private CyclicBarrier cyclicBarrier;

        public SelectPro(int index, CyclicBarrier cyclicBarrier) {
            this.index = index;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {

            try {
                Thread.sleep(new Random().nextInt(10) * 1000);
                System.out.println("element " + index + "connect succeed ！");

                cyclicBarrier.await();
                Thread.sleep(new Random().nextInt(3) * 1000);
                System.out.println("element " + index + "select result: ok!");

                cyclicBarrier.await();


            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }


    public static void main(String[] args) {

        int count = 6;

        CyclicBarrier cyclicBarrier = new CyclicBarrier(6, new Runnable() {
            @Override
            public void run() {
                System.out.println("**** barrier **************");
            }
        });
        for (int i = 0; i < count; i++) {
            SelectPro selectPro = new SelectPro(i,cyclicBarrier);
            Thread thread = new Thread(selectPro);
            thread.start();
        }

    }
}
